<template>
	<div style="width: 1350px;">
		<div class="xiaoquxuanze">
			<el-input placeholder="可搜索房屋/姓名/手机号" style="width: 280px; height: 35px; margin-top: 16px;"></el-input>
			<div>
				<span class="ysxq">演示小区</span>
			</div>
			<div class="tree">
				<el-tree style="max-width: 600px" :data="fwdata" :props="fwdefaultProps"
					@node-click="fwhandleNodeClick" />
			</div>
		</div>
		<div class="wushuju" v-if="currentView === 'wushuju'">
			<img src="../img/前台.png" width="300px" height="300px" />
			<div>请搜索或选择房间进行收款操作</div>
		</div>
		<!-- 房屋数据 -->
		<div class="fwshuju" v-if="currentView === 'fwshuju'">
			<div class="fwxinxi">
				<div class="sj_top">
					<div class="adress">
						{{housexinxi.region_name}}-{{housexinxi.building_name}}-{{housexinxi.unit_name}}-{{housexinxi.house_number}}>
					</div>
					<div class="tag">
						<el-tag type="warning">{{housexinxi.occupancy_status}}</el-tag>
						<el-tag type="warning" style="margin-left: 10px;">{{housexinxi.renovation_status}}</el-tag>
						<el-tag type="warning" style="margin-left: 10px;">{{housexinxi.sale_status}}</el-tag>
					</div>
				</div>
				<div class="mj">面积:{{housexinxi.area_interior}}㎡</div>
			</div>
			<div class="fwsj_biao">
				<div class="sx">
					<button class="gjsx" @click="dialogFormVisible = true">高级筛选<img src="../img/高级筛选.png"
							style="height: 10px;" /></button>
					<el-input class="input" v-model="inputValue" placeholder="费用编号/费用金额">
						<template #append>
							<el-button @click="sousuo"><el-icon>
									<search />
								</el-icon>搜索</el-button>
						</template>
					</el-input>
					<div class="jine">
						<span class="je">总金额:</span>
						<span class="money">¥{{yfk}}</span>
						<el-button class="shoukuan" :disabled="!hasSelected" @click="skdialogFormVisible=true">收款</el-button>
					</div>
				</div>
				<el-dialog v-model="dialogFormVisible" title="高级筛选" width="900px">
					<div style="margin-top: 20px;margin-left: 50px;width: 300px;">
						<el-form-item label="费用所属月" style="width: 300px;">
							<el-date-picker v-model="FeiYong.fyssy" value-format="YYYY-MM-DD" type="month"
								placeholder="请选择年月" />
						</el-form-item>
					</div>
					<div style="margin-top: -50px;margin-left: 440px;width: 300px;">
						<el-form-item label="计费项目" style="width: 300px;">
							<el-select v-model="FeiYong.billingltems_name" clearable placeholder="全部"
								style="width: 240px">
								<el-option v-for="item in jfxmoptions" :key="item.billingltems_name"
									:label="item.billingltems_name" :value="item.billingltems_name" />
							</el-select>
						</el-form-item>
					</div>
					<div style="margin-top: 20px;margin-left: 62px;width: 350px;">
						<el-form-item label="生成时间" style="width: 350px;">
							<el-date-picker v-model="FeiYong.sc_time" value-format="YYYY-MM-DD" type="daterange"
								range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
						</el-form-item>
					</div>
					<template #footer>
						<div class="dialog-footer">
							<el-button @click="dialogFormVisible" style="background-color: white;">
								重置
							</el-button>
							<el-button type="primary" @click="fycha"
								style="background-color: #00C35D;color: white;border: none;">
								确定并查询
							</el-button>
						</div>
					</template>
				</el-dialog>
				<!-- 收款弹窗 -->
				<el-dialog v-model="skdialogFormVisible" title="收款" width="800px">
					<div style="display: grid; grid-template-columns: 400px 350px; gap: 10px;">
						<div style="border-right: 1px dashed #ccc;">
							<el-form-item label="收款方式:" style="width: 350px; margin-top: 20px; margin-left: 50px;">
								<el-select v-model="value" clearable placeholder="请选择" style="width: 240px">
									<el-option v-for="item in options" :key="item.value" :label="item.label"
										:value="item.value" />
								</el-select>
							</el-form-item>
							<el-form-item label="收款金额:" style="width: 350px; margin-top: 20px; margin-left: 50px;">
								<el-input class="input" v-model="yfk" style="width: 240px" />
							</el-form-item>
							<el-input style="width: 320px; margin-left: 10px;" class="gdnr" maxlength="1000"
								placeholder="备注(选填)" show-word-limit type="textarea" />
							<el-dialog v-model="dialogVisible">
								<img w-full :src="dialogImageUrl" alt="Preview Image" />
							</el-dialog>
						</div>
						<div>
							<!-- 第二个 div 的内容 -->
							<div style="border-bottom: 1px dashed #ccc;height:130px;">
								<span style="position: relative;right: 100px;top: 20px;">费用金额</span>
								<span style="position: relative;right: -100px;top: 20px;">{{yfk}}</span>
							</div>
							<div style="height:70px;">
								合计:<span style="font-weight: bold;color: #00C35D;font-size: 20px;">
									¥{{yfk}}
								</span>
							</div>
						</div>
					</div>
					<template #footer>
						<div class="dialog-footer">
							<el-button @click="dialogFormVisible" style="background-color: white;">
								取消
							</el-button>
							<el-button type="primary" @click="ShouKuan"
								style="background-color: #00C35D;color: white;border: none;">
								确定
							</el-button>
						</div>
					</template>
				</el-dialog>
				<div class="FeiYongLB">
					<el-table ref="multipleTableRef" @selection-change="handleSelectionChange"
						:data="formattedHousecost " style="width: 100%">
						<el-table-column fixed="left" type="selection" width="55" />
						<el-table-column v-if="false" prop="cost_id" label="费用id" width="80" />
						<el-table-column label="费用编号" prop="cost_number" width="120" align="center" />
						<el-table-column label="收费项目" prop="billingltems_name" width="120" align="center" />
						<el-table-column label="所属月" prop="formatted_fyssy" width="160" align="center" />
						<el-table-column label="费用起止时间" prop="fyqz_time" width="280" align="center" />
						<el-table-column label="费用金额" prop="fyje" width="80" align="center" />
						<el-table-column label="应付款金额" prop="yfkje" width="200" align="center" />
						<el-table-column prop="formatted_sc_time" label="创建时间" width="180" />
						<el-table-column prop="" label="备注" width="120" />
						<el-table-column fixed="right" label="操作" width="80" align="center">
							<template #default="scope">
								<el-button link type="primary" size="small" @click="orderdetail">详情</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div class="demo-pagination-block">
					<el-pagination v-model:current-page="fwcurrentPage4" v-model:page-size="fwpageSize4"
						:page-sizes="[20, 30, 40, 50]" :size="fwsize" :disabled="fwdisabled" :background="fwbackground"
						layout="total, sizes, prev, pager, next, jumper" :total="fwtotal"
						@size-change="fwhandleSizeChange" @current-change="fwhandleCurrentChange" />
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
	
	import { ElMessage } from 'element-plus'
	import { ref, reactive, watch, computed } from 'vue';
	import $http from '../router/AxiosApi';
	import type { ComponentSize } from 'element-plus'
	const dialogFormVisible = ref(false)
	const skdialogFormVisible = ref(false)
	const fwpage = ref(1)
	const fwpageSize = ref(12)
	const fwtotal = ref(0)
	const fw_size = ref(10)
	const fwsize = ref<ComponentSize>('default')
	const fwcurrentPage4 = ref(1)
	const fwpageSize4 = ref(12)
	const fwbackground = ref(false)
	const fwdisabled = ref(false)
	const fwhandleSizeChange = (val : number) => {
		fwpageSize.value = val;
		fwfylb(fwpage.value, fwpageSize.value, House_id.value, FeiYong.fyssy, FeiYong.billingltems_name, startTime.value, endTime.value, FeiYong.fyje, FeiYong.cost_number)
	}
	const fwhandleCurrentChange = (val : number) => {
		fwpage.value = val;
		fwfylb(fwpage.value, fwpageSize.value, House_id.value, FeiYong.fyssy, FeiYong.billingltems_name, startTime.value, endTime.value, FeiYong.fyje, FeiYong.cost_number)
	}

	interface Tree {
		id : number,
		label : string
		children ?: Tree[]
	}
	const housexinxi = reactive({
		region_name: '',
		building_name: '',
		unit_name: '',
		house_number: '',
		area_interior: '',
		occupancy_status: '',
		renovation_status: '',
		sale_status: '',
		fyssy: '',
		fyqz_time: ''
	})
	const currentView = ref('wushuju')
	const housecostdata = reactive({
		housecost: []
	});
	let totalAmount = null
	const House_id = ref(null)
	const fwhandleNodeClick = (data : Tree) => {
		// 判断是否是叶子节点（没有 children 或 children 为空）
		if (!data.children || data.children.length === 0) {
			console.log("点击的房号 ID:", data.id);
			// 更新 House_id 的值
			House_id.value = data.id;
			$http.post(`/FanWuXinXi/${data.id}`).then((res) => {
				console.log("房屋信息:", res.data.data[0]);
				housexinxi.region_name = res.data.data[0].region_name
				housexinxi.building_name = res.data.data[0].building_name
				housexinxi.unit_name = res.data.data[0].unit_name
				housexinxi.house_number = res.data.data[0].house_number
				housexinxi.area_interior = res.data.data[0].area_interior
				housexinxi.occupancy_status = res.data.data[0].occupancy_status
				housexinxi.renovation_status = res.data.data[0].renovation_status
				housexinxi.sale_status = res.data.data[0].sale_status
				housexinxi.fyqz_time = res.data.data[0].fyqz_time
				currentView.value = 'fwshuju'
				fwfylb(fwpage, fwpageSize, House_id.value, FeiYong.fyssy, FeiYong.billingltems_name, startTime.value, endTime.value, FeiYong.fyje, FeiYong.cost_number)
			});

		} else {
			console.log("点击的是非叶子节点");
		}
	}
	watch(House_id, (newVal, oldVal) => {
		console.log("House_id 更新了:", newVal);
	});
	const fwfylb = (housepage, size, houseId, costssy, jfxm, kssj, jssj, fy, bh) => {
		$http.post(`ParkCost?currentPage=${fwpage.value}&pageSize=${size.value}`, {
			"house_id": houseId,
			"fyssy": costssy,
			"billingltems_name": jfxm,
			"start_time": kssj,
			"end_time": jssj,
			"fyje": fy,
			"cost_number": bh
		}).then((res) => {
			console.log("房屋费用:", res.data.data.list)
			housecostdata.housecost = res.data.data.list
			fwtotal.value = res.data.data.total
			fwcurrentPage4.value = res.data.data.pageNum
			fwpageSize4.value = res.data.data.pageSize
			// 通过 map 获取所有应付款金额
			const amounts = housecostdata.housecost.map(item => parseFloat(item.yfkje) || 0);
			// 使用 reduce 计算总和
			totalAmount = amounts.reduce((sum, amount) => sum + amount, 0);
		})
	}

	const formattedHousecost = computed(() => {
		return housecostdata.housecost.map(item => {
			// 处理 fyssy 字段
			const date = new Date(item.fyssy);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const formattedDate = `${year}-${month}`;

			// 处理 sc_time 字段
			const scdate = new Date(item.sc_time);
			const scyear = scdate.getFullYear();
			const scmonth = String(scdate.getMonth() + 1).padStart(2, '0');
			const scday = String(scdate.getDate()).padStart(2, '0');
			const schours = String(scdate.getHours()).padStart(2, '0');
			const scminutes = String(scdate.getMinutes()).padStart(2, '0');
			const scseconds = String(scdate.getSeconds()).padStart(2, '0');

			const scformattedDate = `${scyear}-${scmonth}-${scday} ${schours}:${scminutes}:${scseconds}`;

			return {
				...item,
				formatted_fyssy: formattedDate,
				formatted_sc_time: scformattedDate
			};
		});
	});
	const fwdefaultProps = {
		children: 'children',
		label: 'label',
		id: 'id'
	}

	const fwdata = ref<Tree[]>([
		{
			id: 1,
			label: '房屋',
			children: [
			],
		}
	])


	$http.post("orderfindAll").then((res) => {
		console.log(res.data.data);
		const regions = {};

		// 将从接口获取的数据整理成层次分明的树状结构
		res.data.data.forEach(item => {
			const { regionName, buildingName, unitName, houseNumber, regionId, buildingId, unitId, houseId } = item;

			// 检查是否已经存在对应的区域节点，如果不存在则创建并将其加入到fwdata.value[0].children中
			if (!regions[regionName]) {
				regions[regionName] = { id: regionId, label: regionName, children: [] };
				fwdata.value[0].children.push(regions[regionName]);
			}

			// 在区域节点下检查是否存在对应的楼栋节点，如果不存在则创建并添加到区域节点的子节点中
			let buildingNode = regions[regionName].children.find(b => b.id === buildingId);
			if (!buildingNode) {
				buildingNode = { id: buildingId, label: buildingName, children: [] };
				regions[regionName].children.push(buildingNode);
			}

			// 在楼栋节点下检查是否存在对应的单元节点，如果不存在则创建并添加到楼栋节点的子节点中
			let unitNode = buildingNode.children.find(u => u.id === unitId);
			if (!unitNode) {
				unitNode = { id: unitId, label: unitName, children: [] };
				buildingNode.children.push(unitNode);
			}

			// 将房号作为子节点添加到对应的单元节点下
			unitNode.children.push({ id: houseId, label: houseNumber });
		});

		console.log("房屋", fwdata);
	});

	const orderdetail = () => {

	}
	const FeiYong = reactive({
		fyssy: '',
		fyqz_time: '',
		billingltems_name: '',
		sc_time: [],
		fyje: '',
		cost_number: ''
	})
	// 用于存储开始时间和结束时间
	const startTime = ref('');
	const endTime = ref('');

	// 监听 sc_time 的变化，并更新 startTime 和 endTime
	watch(() => FeiYong.sc_time, (newVal) => {
		if (Array.isArray(newVal) && newVal.length === 2) {
			const [start, end] = newVal;
			startTime.value = start || '';
			endTime.value = end || '';
			console.log('开始时间:', startTime.value);
			console.log('结束时间:', endTime.value);
		}
	},
		{ immediate: true }  // 立即执行一次，确保初始值被处理
	);
	const inputValue = ref('');
	const fycha = () => {
		dialogFormVisible.value = false
		fwfylb(fwpage, fwpageSize, House_id.value, FeiYong.fyssy, FeiYong.billingltems_name, startTime.value, endTime.value, FeiYong.fyje, FeiYong.cost_number)
	}
	//搜索
	const sousuo = () => {
		FeiYong.fyje = inputValue.value
		FeiYong.cost_number = inputValue.value
		fwfylb(fwpage, fwpageSize, House_id.value, FeiYong.fyssy, FeiYong.billingltems_name, startTime.value, endTime.value, FeiYong.fyje, FeiYong.cost_number)
	}
	let jfxmoptions = reactive([])
	$http.post("/BillingltemsList").then((res) => {
		jfxmoptions = res.data.data
		console.log("计费项目", res.data)
	})

	const value = ref('')
	const options = [
		{
			value: '现金支付',
			label: '现金支付',
		},
		{
			value: '微信支付',
			label: '微信支付',
		},
		{
			value: '支付宝支付',
			label: '支付宝支付',
		}
	]
	const dialogImageUrl = ref('')
	const dialogVisible = ref(false)
	
	const selectedRows = ref([]);
	const selectedCostIds = ref([]); // 用于存储选中的费用id
	const yfk = computed(() => {
		// 如果有选中的行，计算选中行的总金额
		if (selectedRows.value.length > 0) {
			return selectedRows.value.reduce((total, row) => total + (parseFloat(row.yfkje) || 0), 0);
		}
		// 否则，计算表中所有数据的总金额
		return formattedHousecost.value.reduce((total, row) => total + (parseFloat(row.yfkje) || 0), 0);
	});
	function handleSelectionChange(selected) {
		selectedRows.value = selected;
		selectedCostIds.value = selected.map(item => item.cost_id);
		console.log("cost_id",selectedCostIds.value)
	}
	const ShouKuan = () => {
		if(!value.value){
			ElMessage.error('付款方式不能为空！');
			return;
		}
		$http.post(`/ShouQuanFei`,selectedCostIds.value).then((res) => {
			skdialogFormVisible.value = false
			fwfylb(fwpage, fwpageSize, House_id.value, FeiYong.fyssy, FeiYong.billingltems_name, startTime.value, endTime.value, FeiYong.fyje, FeiYong.cost_number)
		})
		ElMessage({
			message: '收款成功',
			type: 'success',
			plain: true,
		})
	}
	const hasSelected = computed(() => selectedRows.value.length > 0);
</script>

<style scoped>
	.xiaoquxuanze {
		border-radius: 10px;
		width: 300px;
		height: 780px;
		float: left;
		background-color: white;
	}

	.ysxq {
		font-weight: bold;
		position: relative;
		right: 105px;
		top: 10px;
	}

	.tree {
		width: 270px;
		position: relative;
		top: 10px;
		margin-left: 15px;
		margin-top: 10px;
	}

	.wushuju {
		width: 1030px;
		margin-left: 320px;
		height: 650px;
		background-color: white;
		border-radius: 10px;
	}

	.wushuju img {
		margin-top: 100px;
	}

	.fwshuju {
		width: 1030px;
		margin-left: 320px;
		height: 650px;
	}

	.cwshuju {
		width: 1030px;
		margin-left: 320px;
		height: 650px;
	}

	.clshuju {
		width: 1030px;
		margin-left: 320px;
		height: 650px;
	}

	.sj_top {
		height: 35px;
		display: flex;
		/* 设置为 flex 容器 */
		align-items: center;
		/* 垂直居中子元素 */
		justify-content: space-between;
		/* 子元素之间均匀分布，两端对齐 */
	}

	.adress {
		width: 250px;
		font-weight: bold;
		font-size: 20px;
		display: flex;
		justify-content: flex-start;
	}

	.tag {
		margin-right: 550px;
		width: 300px;
	}

	.mj {
		float: left;
		font-size: 13px;
	}

	.fwsj_biao {
		width: 1030px;
		height: 700px;
		margin-top: 35px;
		background-color: white;
		border-radius: 10px;
	}

	.cwsj_biao {
		width: 1030px;
		height: 700px;
		margin-top: 35px;
		background-color: white;
		border-radius: 10px;
	}

	.clsj_biao {
		width: 1030px;
		height: 700px;
		margin-top: 35px;
		background-color: white;
		border-radius: 10px;
	}

	.sx {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		/* 确保 sx 容器占满父容器的宽度 */
		padding-top: 15px;
	}

	.gjsx {
		background-color: white;
		border: 1px solid #CCC;
		font-size: 13px;
		margin-right: 20px;
		/* 调整间距 */
		margin-left: 10px;
	}

	.input {
		width: 250px;
		margin-right: 20px;
		/* 调整间距 */
	}

	.jine {
		display: flex;
		align-items: center;
		margin-left: auto;
		/* 推到容器的右边 */
	}

	.je {
		font-size: 13px;
	}

	.money {
		margin-right: 130px;
		font-weight: bold;
		color: #00C35D;
		font-size: 27px;
	}

	.shoukuan {
		background-color: #00C35D;
		color: white;
		margin-right: 30px;
		width: 120px;
		height: 40px;
		font-weight: bolder;
	}

	.FeiYongLB {
		margin-top: 10px;
		height: 590px;
	}

	.demo-pagination-block {
		margin-left: 15px;
	}
</style>